﻿using Microsoft.Office.Interop.Word;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tool.Helper
{
    public class JsonHelper
    {
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="jsonFilePath">JSON文件路径</param>
        /// <returns></returns>
        public static T  ReadData<T>(string jsonFilePath,bool returnEmpty=false) where T : class, new()
        {
            if (File.Exists(jsonFilePath))
            {
                try
                {
                    string jsonString = File.ReadAllText(jsonFilePath);
                    return JsonConvert.DeserializeObject<T>(jsonString);
                }
                catch(Exception ex)
                {
                    LogHelper.LogError(ex);
                }
            }
            if (returnEmpty)
            {
                return new T();
            }
            return null;
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="data">数据</param>
        /// <param name="jsonFilePath">JSON文件路径</param>
        /// <returns></returns>
        public static bool SaveData<T>(T data,string jsonFilePath) where T : class, new()
        {
            try
            {
                FileHelper.EnsureFileExists(jsonFilePath);
                string json = JsonConvert.SerializeObject(data,Formatting.Indented);
                File.WriteAllText(jsonFilePath, json, System.Text.Encoding.UTF8);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex);
            }
            return false;

        }
}
}



